<template>
  <div class="app-container">
    <div class="app-title">
      <span>指标工资项配置</span>
    </div>
    <!-- 切换按钮 -->
    <el-row :gutter="20">
      <el-col :span="8">
        <el-col :span="1">
          <i :class="[treeShow ? 'el-icon-s-fold treeI' : 'el-icon-s-unfold treeI']" @click="toggerTree" />
        </el-col>
      </el-col>
      <div class="filter-container">
        <el-col style="text-align:right;margin-top: -8px;" :span="16">
          <el-button size="small" class="filter-item" style="margin-left:10px;" type="primary" @click="handleQuery">
            查询
          </el-button>
          <el-button size="small" class="filter-item" style="margin-left: 10px;" type="primary" @click="handleEdit">
            编辑
          </el-button>
          <el-button size="small" class="filter-item" style="margin-left: 10px;" type="primary"
            @click="handleBatchEdit">
            批量编辑
          </el-button>
        </el-col>
      </div>
    </el-row>
    <div class="grid-content bg-purple" />
    <div ref="box" class="box">
      <div class="left" :class="[isActive ? 'wid' : 'wids']">
        <div :class="[treeShow ? 'treeShow' : 'treeNotShow']" :style="{ 'height': treeHeight + 'px' }">
          <AgencyTree class="agencyTree" @handleTreeQuery="handleTreeQuery"
            @getFirstAuthAgencyData="getFirstAuthAgencyData" />
        </div>
      </div>
      <div v-show="Show" class="resize" title="收缩侧边栏" />
      <div class="mid" :class="[isActive ? 'mids' : 'min']">
        <!-- 表格部分 -->
        <el-table ref="singalTable" v-loading="listLoading" :data="listData" :stripe="true" :height="tableHeight" fit
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }">
          <template slot="empty">
            <tableEmpty />
          </template>
          <el-table-column type="selection" align="center" width="55" />
          <el-table-column type="index" align="center" width="80" label="序号" />
          <el-table-column label="单位" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.agencyName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="工资项" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.salaryBaseName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="工资类别" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.personStateName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="收款户" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.payeeAcctName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="收款户账号" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.payeeAcctNo }}</span>
            </template>
          </el-table-column>
          <el-table-column label="收款户银行" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.payeeAcctBankName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center">
            <template slot-scope="{ row }">
              <span>{{ row.remark }}</span>
            </template>
          </el-table-column>
        </el-table>
        <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
      </div>
      <Drag ref="icon" />
    </div>
    <!-- 查询 -->
    <el-dialog v-dialogDrag title="查询" :visible.sync="dialogQueryFormVisible" style="padding: 0px" width="50%">
      <el-form ref="queryForm" class="dialog-Backgroundcolor" :model="listQuery" label-position="right"
        label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工资项:">
              <el-select v-model="listQuery.salaryBaseId" clearable placeholder="--请选择--">
                <el-option v-for="item in salaryDataLists" :key="item.id" :label="item.salaryName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工资类别:">
              <el-select v-model="listQuery.personState" clearable placeholder="--请选择--">
                <el-option v-for="item in meritPayList" :key="item.name" :label="item.name" :value="item.code" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" style="margin-top: 10px">
            <el-form-item label="收款户:">
              <el-select v-model="listQuery.payeeAcctId" clearable placeholder="--请选择--">
                <el-option v-for="item in payAccountList" :key="item.id" :label="item.showName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" style="margin-top: 10px">
            <el-form-item label="收款户银行：">
              <el-input v-model="listQuery.payeeAcctBankName" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-button size="small" class="filter-item" style="margin-left: 10px; float: right" type="primary"
            @click="getList">
            查询
          </el-button>
        </el-row>
      </el-form>
    </el-dialog>
    <!-- 编辑页面部分 -->
    <el-dialog v-dialogDrag title="编辑" :close-on-click-modal="false" :visible.sync="editFormVisible"
      style="padding: 0px" width="70%">
      <el-form :rules="listQueryForm" ref="dataForm" class="dialog-Backgroundcolor" :model="listQuery"
        label-position="right" label-width="100px">
        <el-row>
          <el-button size="small" class="filter-item" style="margin-left: 10px; float: right" type="primary"
            @click="handleAdd">
            新增
          </el-button>
          <el-button size="small" class="filter-item" style="margin-left: 10px; float: right" type="primary"
            :loading="saveLoading" @click="handleSave">
            保存
          </el-button>
        </el-row>
        <el-table ref="singalEditTable" v-loading="editTableListLoading" max-height="400" :data="editListData"
          :stripe="true" fit class="editTable" :header-cell-style="{ background: '#eef1f6', color: '#606266' }">
          <template slot="empty">
            <tableEmpty />
          </template>
          <!-- <el-table-column type="selection" align="center" width="55" /> -->
          <el-table-column type="index" align="center" width="80" label="序号" />

          <el-table-column label="工资项" prop="salaryBaseId" align="center" width="140">
            <template slot-scope="scope">
              <el-select v-model="scope.row.salaryBaseId" placeholder="请选择">
                <el-option v-for="item in salaryDataLists" :key="item.id" :label="item.salaryName" :value="item.id" />
              </el-select>
            </template>

          </el-table-column>
          <el-table-column label="工资类别" prop="personState" align="center">
            <template slot-scope="scope">
              <el-select v-model="scope.row.personState" placeholder="请选择">
                <el-option v-for="item in meritPayList" :key="item.code" :label="item.name" :value="item.code" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="收款户" prop="payeeAcctId" align="center">
            <template slot-scope="scope">
              <el-select v-model="scope.row.payeeAcctId" filterable placeholder="请选择">
                <el-option v-for="item in payAccountList" :key="item.id" :label="item.showName" :value="item.id" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" />
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="100">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </el-dialog>
    <!-- 查看页面部分 -->
    <el-dialog v-dialogDrag :close-on-click-modal="false" title="批量编辑" :visible.sync="editBatchFormVisible"
      style="padding: 0px" width="75%">
      <el-form ref="batchDataForm" class="dialog-Backgroundcolor" :rules="registerBatchForm" :model="batchForm"
        label-position="right" label-width="100px">

        <el-row>
          <el-col :span="8">
            <el-form-item label="单位：">
              <el-input v-model="batchSerchAgencyCode" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="银行：" prop="salaCardBank">
              <el-select v-model="batchForm.salaCardBank" placeholder="--请选择--" clearable @change="getCategoryOptions">
                <el-option v-for="item in salaCardBankList" :key="item.code" :label="item.name" :value="item.code" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-table ref="singalBatchEditTable" v-loading="batchTableListLoading" style="margin-top: 10px" max-height="400"
          :data="batchTableDatas" :stripe="true" :header-cell-style="{ background: '#eef1f6', color: '#606266' }">
          <template slot="empty">
            <tableEmpty />
          </template>
          <el-table-column type="selection" align="center" width="50" label="序号" />
          <el-table-column type="index" align="center" width="50" label="序号" />
          <el-table-column label="单位编码" prop="agencyCode" align="center" />
          <el-table-column label="单位名称" prop="agencyName" align="center" />
        </el-table>
        <el-row style="margin-top: 2%; ">
          <el-col :span="8">
            <el-form-item label="工资项：" prop="salaryBaseId">
              <el-select v-model="batchForm.salaryBaseId" filterable placeholder="--请选择--">
                <el-option v-for="item in salaryDataLists" :key="item.id" :label="item.salaryName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工资类别：" prop="personState">
              <el-select v-model="batchForm.personState" filterable placeholder="--请选择--" @change="getCategoryOption">
                <el-option v-for="item in meritPayList" :key="item.code" :label="item.name" :value="item.code" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="收款户：" prop="payeeAcctId">
              <el-select v-model="batchForm.payeeAcctId" filterable placeholder="--请选择--">
                <el-option v-for="item in payAccountList" :key="item.id" :label="item.showName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-button size="small" class="filter-item" style="text-align: center; margin-top: 10px; margin-left: 480px"
          type="primary" :loading="batchSaveLoading" @click="handleBatchSave()">
          保存
        </el-button>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
// import { queryAgencyInfo } from '@/api/unitInformationMaintenance/unitInformationEdit'
import {
  querySalaryBaseItemize,
  selectSalary,
  getAgencyPage,
  queryBaseDataList,
  querySalaryBasedataList,
  queryPayeeAcctList,
  saveSalaryBaseItemize,
  saveSalaryBaseItemizeBatch,
  queryAgencyInfo
} from '@/api/salaryConfigManage/bgtSalaryConfig'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import tableEmpty from '@/components/table/empty'
import AgencyTree from '@/components/tree/agencyTree'
import Drag from '@/components/Drag'
import { getAgencyBank } from '@/api/baseInfo'
export default {
  name: 'Unit',
  components: { Pagination, tableEmpty, AgencyTree, Drag },
  filters: {

  },
  data() {
    return {
      treeHeight: null,
      isActive: true,
      Show: false,
      treeShow: false,
      treeData: '',
      tableHeight: null,
      that: this,
      listData: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 200,
        agencyId: '0',
        salaryBaseId: '',
        personState: '',
        payeeAcctId: '',
        salaCardBank: ''
      },
      batchForm: {
        salaryBaseId: '',
        personState: '',
        payeeAcctId: '',
        remark: '',
        agencyId: '0',
        salaCardBank: '',
        agencyIds: []
      },
      dialogQueryFormVisible: false,
      editFormVisible: false,
      editBatchFormVisible: false,
      salaryDataLists: [],
      salaryDataListgzx: [],
      meritPayList: [],
      payAccountList: [],
      salaCardBankList: [],
      editTableListLoading: false,
      editListData: [],
      batchTableListLoading: false,
      batchTableData: [],
      saveLoading: false,
      batchSaveLoading: false,
      batchSerchAgencyCode: '',
      addItem: {
        agencyId: '',
        // agencyIds: '',
        payeeAcctId: '',
        personState: '',
        salaryBaseId: '',
        isNewItem: ''
      },
      registerBatchForm: {
        salaryBaseId: [
          { required: true, message: '工资项不允许为空', trigger: 'blur' }
        ],
        personState: [
          { required: true, message: '工资类别不允许为空', trigger: 'blur' }
        ],
        payeeAcctId: [
          { required: true, message: '收款户不允许为空', trigger: 'blur' }
        ]
      },
      listQueryForm: {
        salaryBaseId: [
          { required: true, message: '工资项不允许为空', trigger: 'blur' }
        ],
        personState: [
          { required: true, message: '工资类别不允许为空', trigger: 'blur' }
        ],
        payeeAcctId: [
          { required: true, message: '收款户不允许为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    batchTableDatas: function () {
      var search = this.batchSerchAgencyCode
      if (search) {
        return this.batchTableData.filter(function (dataNews) {
          return Object.keys(dataNews).some(function (key) {
            if (key === 'agencyCode' || key === 'agencyName') {
              return String(dataNews[key]).toLowerCase().indexOf(search) > -1
            }
          })
        })
      }
      return this.batchTableData
    }
  },
  watch: {
    // 表格的数据数组
    list(val) {
      this.doLayout()
    }
  },
  created() {
    // this.getList()
    // this.initBaseInfo()
    this.getAgencyInfo()
  },
  mounted() {
    this.getTbHeight()
    this.dragController()
  },
  beforeMount() {
    window.addEventListener('resize', this.getTbHeight)
  },
  methods: {
    getCategoryOptions(code) {
      this.batchForm.salaCardBank = code;
      this.getAgencyInfo()
    },
    getCategoryOption(code) {
      this.batchForm.personState = code;
      this.getAgencyInfo()
    },
    // 拖拽
    dragController() {
      this.$refs.icon.dragControllerDiv()
    },
    toggerTree() {
      this.treeShow = !this.treeShow
      this.isActive = !this.isActive
      this.Show = !this.Show
    },
    handleTreeQuery(data) {
      this.listQuery.agencyId = data.id
      this.addItem.agencyId = data.id
      this.selectSalary()
      this.getList()
    },
    /* 重新渲染table组件 */
    doLayout() {
      this.$nextTick(() => {
        this.$refs.singalTable.doLayout()
      })
    },
    // 获取table高度的方法
    getTbHeight() {
      this.tableHeight = window.innerHeight - 215
      this.treeHeight = this.tableHeight
    },
    // 树返回默认单位信息查询
    getFirstAuthAgencyData(data) {
      this.listQuery.agencyId = data.id
      this.addItem.agencyId = data.id

      this.getList()
      this.initBaseInfo()
    },
    selectSalary() {
      //加载工资项
      selectSalary({ 'agencyId': this.listQuery.agencyId }).then((response) => {
        this.salaryDataListgzx = response.data
      })
    },

    getList() {
      this.listLoading = true
      getAgencyPage(this.listQuery).then((response) => {
        this.listData = response.data.rows
        this.total = response.data.total
        this.listLoading = false
        this.dialogQueryFormVisible = false
      }).catch(() => {
        this.listData = []
        this.total = 0
        this.dialogQueryFormVisible = false
      })
    },
    handleQuery() {
      this.dialogQueryFormVisible = true
    },
    // 编辑
    handleEdit() {
      // const selection = this.$refs.singalTable.selection
      // if (selection.length !== 1) {
      //   this.$message({
      //     showClose: true,
      //     message: '请选择要编辑的数据',
      //     type: 'warning',
      //     duration: 4000
      //   })
      //   return
      // }
      this.editFormVisible = true
      this.editTableListLoading = true

      const params = { 'agencyId': this.listQuery.agencyId, 'salaryBaseId': this.listQuery.salaryBaseId }
      querySalaryBaseItemize(params).then((response) => {
        this.editListData = response.data
        this.editTableListLoading = false
      }).catch(() => {
        this.editTableListLoading = false
      })

    },
    // 批量编辑
    handleBatchEdit() {
      this.batchForm.payeeAcctId = ''
      this.batchForm.personState = ''
      this.batchForm.salaryBaseId = ''
      // this.$refs.singalBatchEditTable.clearFilter()
      this.editBatchFormVisible = true
    },
    // 新增
    handleAdd() {
      const addItem = { ...this.addItem }
      addItem.isNewItem = Math.random()
        .toString(16)
        .substr(2, 8)
      this.editListData.unshift(addItem)
    },
    // 删除
    handleDelete(row) {
      const index = this.editListData.indexOf(row)
      this.editListData.splice(index, 1)
    },

    // 保存
    handleSave() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const a = true
          this.unique().forEach(item => {
            if (item.salaryBaseId === '' || item.personState === '' || item.payeeAcctId === '') {

              this.a = false
              this.saveLoading = false
            }
          })
          if (this.a == false) {
            this.$message({
              showClose: true,
              message: '请将工资项,工资类别,收款户补充完整！',
              type: 'warning',
              duration: 4000
            })
            this.a = true
          } else {

            if (this.unique() == [] || this.unique().length == 0) {
              this.$message({
                showClose: true,
                message: '至少保存一条数据',
                type: 'warning',
                duration: 4000
              })
              this.a = true
              return
            }

            this.saveLoading = true
            saveSalaryBaseItemize(this.unique()).then((response) => {
              this.$message({
                showClose: true,
                message: '保存成功',
                type: 'success',
                duration: 4000
              })
              this.saveLoading = false
              this.editFormVisible = false
              this.getList()
            }).catch(() => {
              this.saveLoading = false
            })
          }
        }
      })
    },
    unique() {
      const editListData = this.editListData
      console.log(editListData)
      const res = new Map()
      return editListData.filter(editData =>
        !res.has(editData.salaryBaseId + editData.personState + editData.payeeAcctId) &&
        res.set(editData.salaryBaseId + editData.personState + editData.payeeAcctId)

      )
    },
    // 批量保存
    handleBatchSave() {
      this.$refs['batchDataForm'].validate(valid => {
        if (valid) {
          console.info('batch save')
          const selection = this.$refs.singalBatchEditTable.selection
          const agencyIds = []
          selection.forEach(item => {
            agencyIds.push(item.id)
          })
          this.batchForm.agencyIds = agencyIds
          this.batchSaveLoading = true
          saveSalaryBaseItemizeBatch(this.batchForm).then((response) => {
            this.$message({
              showClose: true,
              message: '保存成功',
              type: 'success',
              duration: 4000
            })
            this.batchSaveLoading = false
            this.editBatchFormVisible = false
          }).catch(() => {
            this.batchSaveLoading = false
          })

        } else {
          this.$message({
            showClose: true,
            message: '请将必填项补充完整！',
            type: 'warning',
            duration: 4000
          })
        }
      })
    },
    // 查询单位信息
    getAgencyInfo() {
      // const params = { agencyId: '0' }
      // this.listQuery.agencyIds ='0'
      queryAgencyInfo(this.batchForm).then((response) => {
        this.batchTableData = response.data
      })
    },
    // 初始化基础数据
    initBaseInfo() {
      queryBaseDataList().then((response) => {
        this.meritPayList = Object.assign({}, response.data)
      })
      querySalaryBasedataList(this.listQuery).then((response) => {
        this.salaryDataLists = Object.assign({}, response.data)
      })
      queryPayeeAcctList().then((response) => {
        this.payAccountList = Object.assign({}, response.data)
      })
      getAgencyBank().then((response) => {
        this.salaCardBankList = Object.assign({}, response.data)
      })

    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-select {
  .el-input {
    height: auto !important;
  }
}

.editTable {
  ::v-deep .el-input:not(.el-pagination__editor):not(.el-input--mini) {
    width: auto;
  }
}

.redstar .el-form-item__error {
  margin-top: 45px !important;
}
</style>
